# -*- coding:utf-8 -*-

import os
import datetime
from reportlab.lib import colors
from reportlab.lib.units import mm
from reportlab.lib.enums import TA_CENTER, TA_LEFT
from reportlab.lib.styles import ParagraphStyle, getSampleStyleSheet

from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Image, PageBreak, Table, TableStyle

# "宋体"
pdfmetrics.registerFont(TTFont('song', 'simsun.ttf'))

current_path = os.path.abspath(os.path.dirname(os.path.realpath(__file__)))


class PDFGenerator:
    """
    生成pdf报告
    """

    def __init__(self, filename, data):
        self.data = data
        "报告名字"
        self.filename = filename

        "文件名风格"
        self.file_name_style = ParagraphStyle(name='FileNameStyle', fontName='song', fontSize=28,
                                              alignment=TA_CENTER, fontWeight=100)
        "首页正文风格"
        self.home_content_style = ParagraphStyle(name='HomeContentStyle', fontName='song', fontSize=20,
                                                 aligment=TA_LEFT)
        "一级标题风格"
        self.title_style = ParagraphStyle(name="TitleStyle", fontName='song', fontSize=25,
                                          aligment=TA_LEFT, leading=50)
        "二级标题风格"
        self.sub_title_style = ParagraphStyle(name="SubTitleStyle", fontName='song', fontSize=18, aligment=TA_LEFT,
                                              leading=40)
        "文件正文风格"
        self.content_style = ParagraphStyle(name="ContentStyle", fontName='song', fontSize=15, leading=30,
                                            spaceAfter=20, alignment=TA_LEFT, firstLineIndent=30)

        "文件表格风格"
        self.table_style = ParagraphStyle(name="TableStyle", fontName='song', fontSize=15, leading=30,
                                          alignment=TA_CENTER)
        "项目信息表格风格"
        self.project_info_style = TableStyle(
            [
                ('FONTNAME', (0, 0), (-1, -1), 'song'),
                ('FONTSIZE', (0, 0), (-1, -1), 12),
                ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
                ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
                ('BOTTOMPADDING', (0, 0), (-1, -1), 6),
                ('SPAN', (1, 0), (3, 0)),
                ('SPAN', (1, 2), (3, 2)),
                ('SPAN', (1, 3), (3, 3)),
                ('GRID', (0, 0), (-1, -1), 0.5, colors.black),
                ('BACKGROUND', (0, 0), (-1, 0), colors.gray)
            ]
        )
        "项目设备表格风格"
        self.project_equipment_style = TableStyle(
            [
                ('FONTNAME', (0, 0), (-1, -1), 'song'),
                ('FONTSIZE', (0, 0), (-1, -1), 12),
                ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
                ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
                ('BOTTOMPADDING', (0, 0), (-1, -1), 6),
                ('GRID', (0, 0), (-1, -1), 0.5, colors.black),
                ('BACKGROUND', (0, 0), (-1, 0), colors.gray)
            ]
        )
        "项目数据表格风格"
        self.data_info_style = TableStyle(
            [
                ('SPAN', (1, 0), (3, 0)),
                ('SPAN', (1, 4), (3, 4)),
                ('FONTNAME', (0, 0), (-1, -1), 'song'),
                ('FONTSIZE', (0, 0), (-1, -1), 12),
                ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
                ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
                ('BOTTOMPADDING', (0, 0), (-1, -1), 6),
                ('GRID', (0, 0), (-1, -1), 0.5, colors.black),
                ('BACKGROUND', (0, 0), (-1, 0), colors.gray)
            ]
        )
        "项目缺陷表格风格"
        self.defect_info_style = TableStyle(
            [
                ('FONTNAME', (0, 0), (-1, -1), 'song'),
                ('FONTSIZE', (0, 0), (-1, -1), 12),
                ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
                ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
                ('BOTTOMPADDING', (0, 0), (-1, -1), 6),
                ('GRID', (0, 0), (-1, -1), 0.5, colors.black),
                ('BACKGROUND', (0, 0), (-1, 0), colors.gray)
            ]
        )

        "缺陷建议表格风格"
        self.defect_advice_style = TableStyle(
            [
                ('FONTNAME', (0, 0), (-1, -1), 'song'),
                ('FONTSIZE', (0, 0), (-1, -1), 12),
                ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
                ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
                ('BOTTOMPADDING', (0, 0), (-1, -1), 6),
                ('GRID', (0, 0), (-1, -1), 0.5, colors.black),
                ('BACKGROUND', (0, 0), (-1, 0), colors.gray)
            ]
        )

        self.foot_style = ParagraphStyle(name="FootStyle", fontName="song", fontSize=12,
                                         textColor=colors.HexColor(0xB4B4B4),
                                         leading=25, spaceAfter=20, alignment=TA_CENTER, )

    def _gen_file_home(self, store, data):
        """
        生成报告首页，包含名字和报告信息
        :param store:  全局store
        :param data:  传入的数据
        :return:
        """
        "首页内容"
        store.append(Spacer(1, 70 * mm))
        store.append(Paragraph(data["name"], self.file_name_style))

        store.append(Spacer(1, 70 * mm))
        store.append(Paragraph("报告编号：" + data["serial"], self.home_content_style))
        store.append(Spacer(1, 15 * mm))
        store.append(Paragraph("生成日期：" + datetime.datetime.now().strftime('%Y-%m-%d'), self.home_content_style))
        store.append(Spacer(1, 15 * mm))
        store.append(Paragraph("报告名称：" + data["reportName"], self.home_content_style))
        store.append(Spacer(1, 15 * mm))
        store.append(Paragraph("数据来源：" + data["dataFrom"], self.home_content_style))
        store.append(Spacer(1, 35 * mm))
        store.append(Paragraph("内部文档，请勿外传", self.foot_style))

        store.append(PageBreak())

    def _gen_file_title(self, store, data):
        """
        生成一级标题
        :param store: 全局store
        :param data: 传入的数据
        :return:
        """
        store.append(Paragraph(data, self.title_style))

    def _gen_file_sub_title(self, store, data):
        """
        生成二级标题
        :param store: 全局store
        :param data: 传入的数据
        :return:
        """
        store.append(Paragraph(data, self.sub_title_style))

    def _gen_file_content(self, store, data):
        """
        生成文件内容
        :param store: 全局store
        :param data:  传入数据
        :return:
        """
        store.append(Paragraph(data, self.content_style))

    def _gen_file_table(self, store, data, width, style):
        """
        生成表格内容
        :param store
        :param data:
        :param width:
         :param style:
        :return:
        """
        data = Table(data, colWidths=width, rowHeights=10 * mm, style=style)
        store.append(data)
        store.append(Spacer(1, 5 * mm))

    def _gen_file_zhu_image(self, store, image):
        """
        生成柱状图片
        :param store:
        :param image:
        :return:
        """
        img = Image(os.path.join(current_path, "images", image))
        img.drawHeight, img.drawWidth = 250, 400
        store.append(Table([[img]], colWidths=[400]))

    def _gen_file_pie_image(self, store, image):
        """
        生成饼状图片
        :param store:
        :param image:
        :return:
        """
        img = Image(os.path.join(current_path, "images", image))
        img.drawHeight, img.drawWidth = 290, 400
        store.append(Table([[img]], colWidths=[400]))

    def gen_pv_report_pdf(self):
        """
        生成pdf文件
        :param data:  传入的数据
        :return:
        """
        store = []
        # 表格允许单元格内容自动换行格式设置
        stylesheet = getSampleStyleSheet()
        body_style = stylesheet["BodyText"]
        body_style.wordWrap = 'CJK'

        "生成首页"
        self._gen_file_home(store, self.data["home"])

        "生成第二页"
        self._gen_file_title(store, self.data["title"]["title"])

        self._gen_file_content(store, self.data["title"]["content"])

        self._gen_file_title(store, self.data["title2"]["title"])

        self._gen_file_sub_title(store, self.data["title2"]["content"]["sub_title_1"]["title"])

        self._gen_file_table(store, self.data["title2"]["content"]["sub_title_1"]["content"],
                             width=[35 * mm, 35 * mm, 35 * mm, 35 * mm], style=self.project_info_style)

        self._gen_file_sub_title(store, self.data["title2"]["content"]["sub_title_2"]["title"])

        self._gen_file_table(store, self.data["title2"]["content"]["sub_title_2"]["content"],
                             width=[70 * mm, 70 * mm], style=self.project_equipment_style)

        self._gen_file_sub_title(store, self.data["title2"]["content"]["sub_title_3"]["title"])

        self._gen_file_table(store, self.data["title2"]["content"]["sub_title_3"]["content"],
                             width=[70 * mm, 70 * mm], style=self.project_equipment_style)

        self._gen_file_sub_title(store, self.data["title2"]["content"]["sub_title_4"]["title"])

        self._gen_file_table(store, self.data["title2"]["content"]["sub_title_4"]["content"],
                             width=[35 * mm, 35 * mm, 35 * mm, 35 * mm], style=self.data_info_style)

        "生成第三页"
        self._gen_file_title(store, self.data["title3"]["title"])
        self._gen_file_content(store, self.data["title3"]["content"]["content"])
        self._gen_file_table(store, self.data["title3"]["content"]["table"],
                             width=[60 * mm, 40 * mm, 40 * mm], style=self.defect_info_style)

        self._gen_file_sub_title(store, self.data["title3"]["content"]["sub_title_1"]["title"])
        self._gen_file_zhu_image(store, self.data["title3"]["content"]["sub_title_1"]["content"])

        self._gen_file_sub_title(store, self.data["title3"]["content"]["sub_title_2"]["title"])
        self._gen_file_pie_image(store, self.data["title3"]["content"]["sub_title_2"]["content"])

        self._gen_file_sub_title(store, self.data["title3"]["content"]["sub_title_3"]["title"])
        self._gen_file_pie_image(store, self.data["title3"]["content"]["sub_title_3"]["content"])

        "生成第四章节"
        self._gen_file_title(store, self.data["title4"]["title"])

        self._gen_file_sub_title(store, self.data["title4"]["content"]["sub_title_1"]["title"])
        self._gen_file_content(store, self.data["title4"]["content"]["sub_title_1"]["content"])
        self._gen_file_pie_image(store, self.data["title4"]["content"]["sub_title_1"]["image"])

        self._gen_file_sub_title(store, self.data["title4"]["content"]["sub_title_2"]["title"])
        self._gen_file_table(store, self.data["title4"]["content"]["sub_title_2"]["content"],
                             width=[35 * mm, 105 * mm], style=self.defect_advice_style)
        store.append(Paragraph(self.data["title4"]["content"]["sub_title_2"]["attention"], self.foot_style))

        store.append(PageBreak())

        "生成第五章节"
        self._gen_file_title(store, self.data["title5"]["title"])
        self._gen_file_sub_title(store, self.data["title5"]["content"]["flora"]["title"])
        self._gen_file_zhu_image(store, self.data["title5"]["content"]["flora"]["image"])
        store.append(Spacer(1, 15 * mm))
        self._gen_file_sub_title(store, self.data["title5"]["content"]["dust"]["title"])
        self._gen_file_zhu_image(store, self.data["title5"]["content"]["dust"]["image"])
        store.append(PageBreak())
        self._gen_file_sub_title(store, self.data["title5"]["content"]["shit"]["title"])
        self._gen_file_zhu_image(store, self.data["title5"]["content"]["shit"]["image"])
        store.append(Spacer(1, 15 * mm))
        self._gen_file_sub_title(store, self.data["title5"]["content"]["strip"]["title"])
        self._gen_file_zhu_image(store, self.data["title5"]["content"]["strip"]["image"])
        store.append(PageBreak())
        self._gen_file_sub_title(store, self.data["title5"]["content"]["break"]["title"])
        self._gen_file_zhu_image(store, self.data["title5"]["content"]["break"]["image"][0]["image"])
        store.append(Spacer(1, 15 * mm))
        self._gen_file_zhu_image(store, self.data["title5"]["content"]["break"]["image"][1]["image"])

        doc = SimpleDocTemplate(self.filename,
                                leftMargin=20 * mm, rightMargin=20 * mm, topMargin=20 * mm, bottomMargin=20 * mm)
        doc.build(store)


data1 = {
    "home": {
        "name": "无人机智能光伏运维报告",
        "serial": "GF-2020-0001",
        "reportName": "金山光伏项目运维报告",
        "dataFrom": "无人机智能光伏运维平台",
    },
    "title": {
        "title": "一、项目简介",
        "content": "该项目位于上海市金山区漫华路8号，管理方为上海市漕泾光伏发电有限公司，装机容量40WM，占地20亩。"
    },
    "title2": {
        "title": "二、项目信息",
        "content": {
            "sub_title_1": {
                "title": "1、项目信息",
                "content": [
                    ["项目名称", "金山光伏项目一", "", ""],
                    ["项目负责人", "张三", "运营时间", "2018-08-02"],
                    ["所属公司", "上海漕泾发电有限公司", "", ""],
                    ["公司地址", "上海金山区漫华路8号", "", ""]]
            },
            "sub_title_2": {
                "title": "2、设备信息",
                "content": [
                    ["设备", "型号"],
                    ["无人机型号", "大疆经纬M300RTK"],
                    ["镜头型号", "大疆禅思XT2"]
                ]
            },
            "sub_title_3": {
                "title": "3、运维团队",
                "content": [
                    ["角色", "姓名"],
                    ["运维负责人", "张三"],
                    ["飞手", "李四"]
                ]
            },
            "sub_title_4": {
                "title": "4、数据信息",
                "content": [
                    ["项目名称", "金山光伏项目一", "", ""],
                    ["拍摄时间", "2020-05-13", "结束时间", "2020-05-14"],
                    ["飞行架次", "12次", "飞行时间", "6小时"],
                    ["可见光图片数", "10000张", "热成像图片数", "10000张"],
                    ["天气情况", "风力4级，天气比较晴朗", "", ""],
                ]
            }
        }
    },
    "title3": {
        "title": "三、项目诊断",
        "content": {
            "content": "该项目检测光伏数据量10000张，检测到的缺陷类型总计3个类别，缺陷数量300张，缺陷占比达到30%。",
            "table": [
                ["类型", "数量", "占比"],
                ["break(损坏)", "300", "3%"],
                ["shit(鸟屎)", "700", "7%"],
                ["defect(缺陷)", "2000", "20%"],
                ["normal(正常)", "7000", "70%"],
            ],
            "sub_title_1": {
                "title": "1、柱状图",
                "content": "bar_image.png"
            },
            "sub_title_2": {
                "title": "2、饼状图",
                "content": "pie_image.png"
            },
            "sub_title_3": {
                "title": "3、历史运维",
                "content": "pie_image.png"
            },
        }
    },
    "title4": {
        "title": "四、分析建议",
        "content": {
            "sub_title_1": {
                "title": "1、缺陷分析",
                "content": "该项目缺陷类别中，遮挡占比最大，属于可修复性缺陷，该类缺陷形成原因主要是环境因素。",
                "image": "radar_image.png"
            },
            "sub_title_2": {
                "title": "2、修复建议",
                "content": [
                    ["缺陷类型", "修复建议"],
                    ["遮挡", "清除光伏板组件上的草木植被"],
                    ["鸟屎", "清洗光伏板组件上鸟类排泄物"],
                    ["损坏", "根据损坏情况确定是是否更换对应光伏组件"],
                ],
                "attention": "注意：相应修复建议以及修复视频可在光伏运维平台光伏主页查看。"
            }
        }
    }
}

# data = get_project_report_data("jin_shan_guang_fu_xiang_mu_er")
# test_pdf = PDFGenerator(r'C:\Users\Administrator\Desktop\test.pdf', data1)
# test_pdf.gen_pv_report_pdf()
